/**
 * Project Name:hyh-web
 * File Name:LogInterceptor.java
 * Package Name:com.hyh.interceptor
 * Date:2018年8月31日下午2:19:57
 *
*/

package com.hyh.interceptor;

import java.io.BufferedReader;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;

import com.hyh.annotation.SpringHandlerInterceptor;
import com.hyh.logback.LogCvt;

/**
 * ClassName:LogInterceptor
 * Reason:	 TODO ADD REASON.
 * Date:     2018年8月31日 下午2:19:57
 * @author   huangyihao
 * @version  
 * @see 	 
 */
@SpringHandlerInterceptor(includePatterns = "/**" ,order = 0)
public class LogInterceptor implements HandlerInterceptor {
	
	private long begtime = 0l;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Thread.currentThread().setName(request.getSession().getId());
		begtime = System.currentTimeMillis();
		
		LogCvt.info("开始请求 -> " + request.getRequestURL());
		LogCvt.info("Request Uri -> " + request.getRequestURI());
		LogCvt.info("Request Method -> " + request.getMethod());

		Enumeration<String> headers = request.getHeaderNames();
		while(headers.hasMoreElements()) {
			String header = headers.nextElement();
			LogCvt.info("Request Header -> " + header + " : " + request.getHeader(header));
		}
		
		String queryString = request.getQueryString();
		LogCvt.info("Request Params -> " + queryString);
//		LogCvt.info("Request Body -> " + getRequestBody(request));
		
		return HandlerInterceptor.super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if(ex != null){
			LogCvt.error(ex.getMessage(), ex);
		}
		LogCvt.info("完成请求[" + (System.currentTimeMillis() - begtime) + "ms] -> " + request.getRequestURL());
		
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
	
	private String getRequestBody(HttpServletRequest request) throws Exception {
		BufferedReader reader = request.getReader();
		String str = "";
		StringBuffer sb = new StringBuffer();
		while((str = reader.readLine()) != null){
			sb.append(str);
		}
		return sb.toString();
	}
	
}
